<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>章节管理</span>
          <div>
            <el-button
              type="primary"
              icon="Plus"
              class="toolbar-button is-primary"
              @click="handleAdd"
            >新增章节</el-button>
            <el-button
              type="success"
              icon="Sort"
              class="toolbar-button is-success"
              @click="handleSort"
            >排序章节</el-button>
            <el-button
              type="info"
              icon="Back"
              class="toolbar-button is-info"
              @click="$router.push('/classroom/course')"
            >返回课程</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <div class="search-form">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
          <el-form-item label="课程选择" prop="courseId">
            <el-select v-model="queryParams.courseId" placeholder="请选择课程" clearable style="width: 200px" @change="handleQuery">
              <el-option
                v-for="course in courseList"
                :key="course.id"
                :label="course.title"
                :value="course.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="章节名称" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入章节名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="草稿" value="0" />
              <el-option label="已发布" value="1" />
              <el-option label="已下架" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="chapterList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
        <el-table-column label="章节名称" align="left" min-width="200">
          <template #default="scope">
            <div>
              <div class="chapter-title">{{ scope.row.title }}</div>
              <div class="text-muted">{{ scope.row.description || '暂无描述' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属课程" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.courseName || scope.row.courseTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课时数量" align="center" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.lessonCount || 0 }}个</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总时长" align="center" width="100">
          <template #default="scope">
            <span>{{ formatDuration(scope.row.totalDuration) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="info"
                icon="View"
                @click="handleView(scope.row)"
                class="table-operation-button is-info"
                size="small"
              >查看</el-button>
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >编辑</el-button>
              <el-button
                type="success"
                icon="VideoPlay"
                @click="handleLessons(scope.row)"
                class="table-operation-button is-success"
                size="small"
              >课时</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleCopy" icon="DocumentCopy">复制章节</el-dropdown-item>
                    <el-dropdown-item command="handleDelete" icon="Delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改章节对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="chapterFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" style="width: 100%">
            <el-option
              v-for="course in courseList"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="章节名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入章节描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="1" :max="999" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">已发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 章节排序对话框 -->
    <el-dialog title="章节排序" v-model="sortDialogVisible" width="500px" append-to-body>
      <div v-if="queryParams.courseId">
        <p class="sort-tip">拖拽下方章节可调整顺序</p>
        <el-table :data="sortChapterList" row-key="id">
          <el-table-column label="排序" width="80">
            <template #default="scope">
              <el-icon class="drag-handle"><Rank /></el-icon>
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="章节名称" prop="title" />
          <el-table-column label="课时数" prop="lessonCount" width="80" />
        </el-table>
      </div>
      <div v-else class="no-course-selected">
        <el-empty description="请先选择课程" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sortDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSort" :disabled="!queryParams.courseId">保存排序</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Chapter">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Sort, Back, Search, Refresh, View, Edit, VideoPlay, DocumentCopy, Delete, Rank } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getChapterPage,
  getChapterList,
  createChapter,
  updateChapter,
  deleteChapter,
  updateChapterSort,
  getCourseList
} from '@/api/classroom'

const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const open = ref(false)
const sortDialogVisible = ref(false)
const title = ref('')
const queryRef = ref()
const chapterFormRef = ref()

// 列表数据
const chapterList = ref([])
const courseList = ref([])
const sortChapterList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  courseId: route.query.courseId || undefined,
  title: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  courseId: undefined,
  title: undefined,
  description: undefined,
  sortOrder: 1,
  status: 1
})

// 表单校验规则
const rules = reactive({
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'change' }],
  title: [{ required: true, message: '章节名称不能为空', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '排序号不能为空', trigger: 'blur' }]
})

// 获取章节列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getChapterPage(queryParams)
    if (response.code === 200) {
      chapterList.value = response.data.rows || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取章节列表失败')
    }
  } catch (error) {
    console.error('获取章节列表失败:', error)
    ElMessage.error('获取章节列表失败')

    // 模拟数据
    chapterList.value = [
      {
        id: 1,
        courseId: 'course001',
        courseName: 'Java基础教程',
        title: '第一章：Java入门',
        description: 'Java语言基础知识介绍',
        sortOrder: 1,
        lessonCount: 5,
        totalDuration: 3600,
        status: 1,
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        courseId: 'course001',
        courseName: 'Java基础教程',
        title: '第二章：面向对象编程',
        description: 'Java面向对象编程概念和实践',
        sortOrder: 2,
        lessonCount: 8,
        totalDuration: 5400,
        status: 1,
        createTime: '2024-01-15 11:20:00'
      },
      {
        id: 3,
        courseId: 'course002',
        courseName: 'Python数据分析',
        title: '第一章：Python基础',
        description: 'Python语言基础和数据类型',
        sortOrder: 1,
        lessonCount: 6,
        totalDuration: 4200,
        status: 0,
        createTime: '2024-01-15 14:15:00'
      }
    ]
    total.value = 3
  } finally {
    loading.value = false
  }
}

// 获取课程列表
const getCourses = async () => {
  try {
    const response = await getCourseList({ pageNum: 1, pageSize: 100 })
    if (response.code === 200) {
      courseList.value = response.data.rows || []
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    // 模拟数据
    courseList.value = [
      { id: 'course001', title: 'Java基础教程' },
      { id: 'course002', title: 'Python数据分析' },
      { id: 'course003', title: 'Vue.js实战' }
    ]
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加章节'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const chapterId = row.id
  Object.assign(form, row)
  open.value = true
  title.value = '修改章节'
}

// 查看按钮操作
const handleView = (row) => {
  router.push({
    path: '/classroom/chapter/detail',
    query: { id: row.id }
  })
}

// 课时管理
const handleLessons = (row) => {
  router.push({
    path: '/classroom/lesson',
    query: { chapterId: row.id, courseId: row.courseId }
  })
}

// 排序章节
const handleSort = async () => {
  if (!queryParams.courseId) {
    ElMessage.warning('请先选择课程')
    return
  }

  try {
    const response = await getChapterList(queryParams.courseId)
    if (response.code === 200) {
      sortChapterList.value = response.data || []
      sortDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取章节列表失败:', error)
    ElMessage.error('获取章节列表失败')
  }
}

// 提交排序
const submitSort = async () => {
  try {
    const chapters = sortChapterList.value.map((item, index) => ({
      id: item.id,
      sortOrder: index + 1
    }))

    const response = await updateChapterSort(queryParams.courseId, chapters)
    if (response.code === 200) {
      ElMessage.success('排序保存成功')
      sortDialogVisible.value = false
      getList()
    } else {
      ElMessage.error(response.message || '排序保存失败')
    }
  } catch (error) {
    console.error('排序保存失败:', error)
    ElMessage.error('排序保存失败')
  }
}

// 下拉菜单操作
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleCopy':
      handleCopy(row)
      break
    case 'handleDelete':
      handleDelete(row)
      break
  }
}

// 复制章节
const handleCopy = async (row) => {
  try {
    await ElMessageBox.confirm('确定要复制该章节吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const copyData = {
      ...row,
      title: row.title + ' - 副本',
      id: undefined
    }

    const response = await createChapter(copyData)
    if (response.code === 200) {
      ElMessage.success('复制成功')
      getList()
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制失败:', error)
      ElMessage.error('复制失败')
    }
  }
}

// 删除按钮操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除章节"' + row.title + '"吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteChapter(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      getList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    courseId: queryParams.courseId,
    title: undefined,
    description: undefined,
    sortOrder: 1,
    status: 1
  })
  chapterFormRef.value?.resetFields()
}

// 提交表单
const submitForm = () => {
  chapterFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          const response = await updateChapter(form.id, form)
          if (response.code === 200) {
            ElMessage.success('修改成功')
          } else {
            ElMessage.error(response.message || '修改失败')
            return
          }
        } else {
          const response = await createChapter(form)
          if (response.code === 200) {
            ElMessage.success('新增成功')
          } else {
            ElMessage.error(response.message || '新增失败')
            return
          }
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 工具函数
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已下架'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDuration = (seconds) => {
  if (!seconds) return '0分钟'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  }
  return `${minutes}分钟`
}

const parseTime = (time, pattern = '{y}-{m}-{d} {h}:{i}:{s}') => {
  if (!time) return ''
  return time
}

// 页面加载
onMounted(() => {
  getCourses()
  getList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.chapter-title {
  font-weight: 500;
  color: #303133;
}

.sort-tip {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  text-align: center;
}

.drag-handle {
  cursor: move;
  color: #909399;
  margin-right: 8px;
}

.no-course-selected {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  text-align: right;
}

// 分页组件样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: right;
}
</style>
